/***************************************************************************
 *   Copyright (C) 2009 by umbacos@gmail.com                               *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#include "udm-common.h"

extern char* dtrk;
extern char* ctor;
extern char* wget;

void strip_last ( char * str, char ch ) {
	char * entry = rindex ( str, ch );
	if ( entry ) *entry = '\0';
}

char * getPID ( char* file ) {

	FILE * fp;
	char pidf[100];
	char pids[10];
	char exef[1000];
	char * what;
	char * entry;
	char * q;

#ifdef DEBUG
mylog("getPID of:",file);
#endif
	if 	( strstr ( file, FILTER_WGT ) != NULL ) what = wget;
	else if ( strstr ( file, FILTER_TOR ) != NULL ) what = ctor;
	else return "";

#ifdef DEBUG
mylog("type is:",what);
#endif
	chdir ( dtrk );
	entry = strdup ( file );
	strip_last ( entry, '.' );

#ifdef DEBUG
mylog("tokn file is:",entry);
#endif
	if ( ( fp = fopen ( entry, "r" ) ) == NULL ) return "";
	q = fgets ( pids, 10, fp );
	if ( fclose ( fp ) == -1 ) return "";
	strip_last ( pids, '\n' );

#ifdef DEBUG
mylog("look for pid:",pids);
#endif
	memset ( exef, 0, 1000 );
	sprintf ( pidf, "/proc/%s/exe", pids );
	if ( readlink ( pidf, exef, 1000 ) < 0 ) return "";

#ifdef DEBUG
mylog("points to:",exef);
mylog("  what is:",what);
#endif
	if ( strcmp ( exef, what ) == 0 ) return strdup ( pids );

#ifdef DEBUG
mylog("pid not found","");
#endif

	return "";
}
